import { Select, Form, Button, Row, Col, Spin, Alert, Icon } from 'antd';
import _ from 'lodash';

const Option = Select.Option;
const FormItem = Form.Item;

const formLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 }
};
const buttonLayout = {
  span: '18',
  offset: '4'
};

let MachinesForm = ({ fetching, updateMachinesFetching, groupMachines, unit, form, onMachinesUpdate }) => {
  const { id, runtimeId, machineList } = unit;

  if (fetching) {
    return <Spin/>;
  }
  if (_.isEmpty(groupMachines)) {
    return <Alert showIcon type='warning' message='此开发组未被分配任何机器，无机器可用'/>;
  }
  const { getFieldProps, getFieldValue } = form;
  const machinesField = getFieldProps('machines', {
    initialValue: machineList.map(machine => machine.id)
  });

  const onSubmit = (evt) => {
    evt.preventDefault();
    const machineIds = getFieldValue('machines');
    onMachinesUpdate(id, runtimeId, machineIds);
  };

  return (
    <Form horizontal onSubmit={onSubmit}>
      <FormItem label='分配机器：' {...formLayout}>
        <Select multiple {...machinesField} onSearch={(value) => console.log(value)}>
          {groupMachines.map(machine => {
            return <Option key={machine.id} value={machine.id}><Icon type='hdd'/>{machine.ip}</Option>;
          })}
        </Select>
      </FormItem>
      <Row>
        <Col {...buttonLayout}>
          <Button loading={updateMachinesFetching} type='primary' htmlType='submit'>确定</Button>
        </Col>
      </Row>
    </Form>
  );
};
MachinesForm = Form.create()(MachinesForm);

export default MachinesForm;
